package net.yb.servlet;

import net.yb.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * 获取请求参数
         */
        String name = req.getParameter("name");
        String pwd = req.getParameter("pwd");
        int age = Integer.parseInt(req.getParameter("age")); // 将String转换为int
        String sex = req.getParameter("sex");
        double height = Double.parseDouble(req.getParameter("height")); // 将String转换为double
        User user = new User(null, name, pwd, age, sex, height);

        /**
         * 保存到数据库中
         */
        try {
            // 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 获取连接
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/yc12405", "root", "root");
            // 编写sql语句
            String sql = "insert into t_user(name,pwd,age,sex,height) values(?,?,?,?,?)";
            // 创建PreparedStatement对象
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, user.getName());
            ps.setString(2, user.getPwd());
            ps.setInt(3, user.getAge());
            ps.setString(4, user.getSex());
            ps.setDouble(5, user.getHeight());
            // 执行sql语句
            ps.executeUpdate();
            System.out.println("保存成功！");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
